package com.lld.crowdfunding.handler;

import com.lld.crowdfunding.entity.QuanXian;
import com.lld.crowdfunding.entity.User;
import com.lld.crowdfunding.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * cookie记住登录处理器
 */

@Component
public class RemeberLoginIntercepter implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();//获取所有cookie信息
        if(cookies == null) {//若没有cookie则去登录界面登录
            System.out.println("cookie集合为null");
            response.sendRedirect(request.getContextPath()+"/login.html");
            return false;
        }
        String cookieUsername = null;
        for(Cookie item:cookies) {//遍历所有cookie,查找是否有名为cookie_username的cookie(找到不代表具有登录信息)
            if(item.getName().equals("cookie_username")) {
                cookieUsername = item.getValue();//将cookie的内容赋值给字符串cookieUsername
                break;
            }
        }
        if(cookieUsername == "" || cookieUsername == null) {//如果cookie为空说明不具有登录信息
            response.sendRedirect(request.getContextPath()+"/login.html");
            return false;
        }
        //以上情况都没有，说明cookie中具有登录信息

        HttpSession session = request.getSession();
        Object userSession = session.getAttribute("user");//先查找session
        if(userSession == null) {//若session为空，则已经过期，创建session
            User u = userMapper.login(cookieUsername);
            List<QuanXian> userQuanxian = userMapper.getUserQuanxian(u.getId());
            session.setAttribute("quanxian",userQuanxian);
            session.setAttribute("user",u);
        }
        return true;
    }
}
